<?php

namespace App\Admin\Controllers;

use App\OssConfig;
use Carbon\Carbon;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;

class OssConfigController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = 'OSS存储';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new OssConfig());

        $grid->column('name', __('名称'));
        $grid->column('prefix', __('Prefix'));
        $grid->column('access_id', __('Access id'));
        $grid->column('access_key', __('Access key'));
        $grid->column('bucket', __('Bucket'));
        $grid->column('endpoint', __('Endpoint(外)'));
        $grid->column('endpoint_internal', __('Endpoint internal（内）'));
        $grid->column('ssl', __('Ssl'))->using(['否', '是'])->label(['default', 'success']);
        $grid->column('isCName', __('IsCName'))->using(['否', '是'])->label(['default', 'success']);
        $grid->column('debug', __('Debug'))->using(['否', '是'])->label(['default', 'success']);
        $grid->column('enabled', __('启用'))->using(['否', '是'])->label(['default', 'success']);
        $grid->column('updated_at', __('Updated at'))->display(function ($value) {
            return Carbon::parse($value)->toDateString();
        });

        $grid->hideColumns(['ssl', 'isCName', 'debug', 'updated_at']);

        return $grid;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new OssConfig());

        $form->text('name', __('Name'))->required();
        $form->text('access_id', __('Access id'))->required();
        $form->text('access_key', __('Access key'))->required();
        $form->text('bucket', __('Bucket'))->required();
        $form->text('endpoint', __('Endpoint（外）'))->required();
        $form->text('endpoint_internal', __('Endpoint internal(内)'));
        $form->text('prefix', __('Prefix'));

        $form->switch('enabled', __('OSS启用'));
        $form->switch('ssl', __('Ssl'));
        $form->switch('isCName', __('IsCName'));
        $form->switch('debug', __('Debug'));
        $form->text('cdnDomain', __('CdnDomain'));

        $form->embeds('sts', 'sts配置', function ($form) {
            $form->text('acessKeyID');
            $form->text('accessKeySecret');
            $form->text('roleArn');
            $form->text('roleSessionName');
        });

        $form->saved(function (Form $form) {
            $model = $form->model();
            if ($model['enabled']) {
                OssConfig::query()->get()->map(function ($item) use ($model) {
                    if ($item['id'] != $model['id']) {
                        $item->enabled = 0;
                        $item->save();
                    }
                });
            }
        });
        return $form;
    }
}
